package com.blb.zk;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * Zookeeper连接案例
 */
public class ZkDemo {

    private static CountDownLatch countDownLatch = new CountDownLatch(1);
    private static ZooKeeper zooKeeper;
    private static Stat stat = new Stat();

    public void connect(String ip,int port,String watchNode) throws IOException, KeeperException, InterruptedException {
        //创建zk连接客户端
        zooKeeper = new ZooKeeper(ip + ":" + port,3000,new MyZKWatcher());
        //阻塞线程，需要完成连接后再执行
        countDownLatch.await();
        //获得节点的数据
        byte[] data = zooKeeper.getData(watchNode, true, stat);
        String str = new String(data);
        System.out.println(watchNode + "节点值是：" + str);
        Thread.sleep(Integer.MAX_VALUE);
    }

    /**
     * zookeeper 观察者
     */
    static class MyZKWatcher implements Watcher{

        @Override
        public void process(WatchedEvent watchedEvent) {
            //对连接状态进行判断
            if(watchedEvent.getState() == Event.KeeperState.SyncConnected){
                //判断是节点变化事件，还是连接完成事件
                if(watchedEvent.getType() == Event.EventType.None){
                    //连接成功事件，就唤醒连接的线程
                    countDownLatch.countDown();
                }else if(watchedEvent.getType() == Event.EventType.NodeDataChanged){
                    //如果是节点变化事件，读取内容
                    try {
                        byte[] data = zooKeeper.getData(watchedEvent.getPath(),true,stat);
                        System.out.println(watchedEvent.getPath() + "发生了修改:" + new String(data));
                    } catch (KeeperException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        }
    }

    public static void main(String[] args) {
        try {
            new ZkDemo().connect("192.168.223.196",2181,"/hello");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
